import express from 'express';
import { PORT } from './config';
import cors from './util/cors';
import ip from 'ip';
import dayjs from 'dayjs';
import bodyParser from 'body-parser';
import { fileFormat, mkdirs, deleteFolderRecursive, firstTimeCreationUser } from './util/';
import swaggerInstall from './util/swagger';
import ApiHtml from './router/apiHtml';
import ApiUpload from './router/upload';
import ApiUser from './router/user';
import ApiAdaptor from './router/adaptor';
import ApiMeasure from './router/measure';
import path from 'path';
import fs from 'fs';

const app = express();

app.use(bodyParser.json()); // json 解析
app.use(bodyParser.raw()); // raw 解析
app.use(bodyParser.text()); // text 解析
app.use(bodyParser.urlencoded({ extended: true })); // x-www-form-urlencoded 解析

swaggerInstall(app); // swagger接口文档

app.use(cors); // 跨域 cors

app.all('*', (req: any, res, next) => { // 设置允许跨域请求
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Credentials', 'true');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Metheds', 'PUT, POST, GET, DELETE, OPTIONS');
  res.header('X-Powered-By', 'nodejs');
  res.header('Content-Type', 'application/json;charset=utf-8');
  if (req.url === '/' || req.url === '/api' || req.url === '/api/') return res.redirect('/node/api/doc');
  next();
});

// 读取静态文件
app.use(express.static(path.join(__dirname, './static')));

const dir = path.join(__dirname, './static/temporary/');

mkdirs(dir); // 目录不存在即创建目录

app.get('/node/staticFile/:file/:name', (req, res) => {
  try {
    fs.statSync(path.join(__dirname, `./static/${req.params.file}/${req.params.name}`));
    res.set({
      'Content-Type': fileFormat(req.params.name) // 设置响应的 Content-Type
      // 'Content-Disposition': 'attachment', // 设置响应的 Content-Disposition，用于告诉浏览器下载文件
    });
    res.sendFile(path.join(__dirname, `./static/${req.params.file}/${req.params.name}`));
  } catch (error) {
    res.send({ code: 404, msg: `${req.params.name}暂无资源文件` });
  }
});
app.get('/node/staticFile/:file1/:file2/:name', (req, res) => {
  try {
    fs.statSync(path.join(__dirname, `./static/${req.params.file1}/${req.params.file2}/${req.params.name}`));
    res.set({ 'Content-Type': fileFormat(req.params.name) });
    res.sendFile(path.join(__dirname, `./static/${req.params.file1}/${req.params.file2}/${req.params.name}`));
  } catch (error) {
    res.send({ code: 404, msg: `${req.params.name}暂无资源文件` });
  }
});
app.get('/node/staticFile/:file1/:file2/:file3/:name', (req, res) => {
  try {
    fs.statSync(path.join(__dirname, `./static/${req.params.file1}/${req.params.file2}/${req.params.file3}/${req.params.name}`));
    res.set({ 'Content-Type': fileFormat(req.params.name) });
    res.sendFile(path.join(__dirname, `./static/${req.params.file1}/${req.params.file2}/${req.params.file3}/${req.params.name}`));
  } catch (error) {
    res.send({ code: 404, msg: `${req.params.name}暂无资源文件` });
  }
});

// 定时删除临时文件夹
setInterval(() => {
  deleteFolderRecursive(dir);
}, 1000 * 60 * 60 * 21); // 21小时

ApiHtml(app);
ApiUpload(app);
ApiUser(app);
ApiAdaptor(app);
ApiMeasure(app)

setTimeout(() => {
  app.listen(PORT, () => {
    console.log(`http://${ip.address()}:${PORT}  服务已启动${dayjs().format('YYYY-MM-DD HH:mm:ss')}`);
  });
  firstTimeCreationUser();
}, 1000);
